// frontend/src/utils/api.js
import axios from 'axios';

// 创建 axios 实例
const apiClient = axios.create({
  baseURL: '/api', // 使用相对路径，通过代理转发
  timeout: 10000,
});

// 请求拦截器 - 添加 JWT token
apiClient.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem('token');
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 响应拦截器 - 处理错误
apiClient.interceptors.response.use(
  (response) => {
    return response;
  },
  (error) => {
    if (error.response?.status === 401) {
      // 检查是否是登录请求，如果是，则不进行重定向
      const requestPath = error.config?.url || '';
      if (requestPath.includes('/auth/login')) {
        // 登录请求失败，直接返回错误，不进行重定向
        return Promise.reject(error);
      }
      
      // 防止重复处理和无限重定向
      const currentPath = window.location.pathname;
      
      // 如果已经在登录页，不重复清除和跳转
      if (currentPath !== '/login') {
        // Token 过期或无效，跳转到登录页
        localStorage.removeItem('token');
        localStorage.removeItem('user');
        localStorage.removeItem('role');
        window.location.href = '/login';
      }
    }
    return Promise.reject(error);
  }
);

// 产品管理相关 API
export const productAPI = {
  // 获取产品列表
  getProducts: (params = {}) => apiClient.get('/products', { params }),
  
  // 获取单个产品
  getProduct: (id) => apiClient.get(`/products/${id}`),
  
  // 创建产品
  createProduct: (data) => apiClient.post('/products', data),
  
  // 更新产品
  updateProduct: (id, data) => apiClient.put(`/products/${id}`, data),
  
  // 删除产品
  deleteProduct: (id) => apiClient.delete(`/products/${id}`),
};

// 兑换码管理相关 API
export const exchangeCodeAPI = {
  // 获取兑换码列表
  getExchangeCodes: (params = {}) => apiClient.get('/exchange-codes', { params }),
  
  // 获取单个兑换码
  getExchangeCode: (id) => apiClient.get(`/exchange-codes/${id}`),
  
  // 创建兑换码
  createExchangeCode: (data) => apiClient.post('/exchange-codes', data),
  
  // 更新兑换码
  updateExchangeCode: (id, data) => apiClient.put(`/exchange-codes/${id}`, data),
  
  // 删除兑换码
  deleteExchangeCode: (id) => apiClient.delete(`/exchange-codes/${id}`),
  
  // 批量生成兑换码
  batchGenerateCodes: (data) => apiClient.post('/exchange-codes/batch-generate', data),
};

// 商家管理相关 API
export const merchantAPI = {
  // 获取商家列表
  getMerchants: (params = {}) => apiClient.get('/admin/merchants', { params }),
  
  // 获取单个商家
  getMerchant: (id) => apiClient.get(`/admin/merchants/${id}`),
  
  // 更新商家
  updateMerchant: (id, data) => apiClient.put(`/admin/merchants/${id}`, data),
  
  // 更新商家状态
  updateMerchantStatus: (id, status) => apiClient.put(`/admin/merchants/${id}/status`, { status }),
};

// 订单管理相关 API
export const orderAPI = {
  // 获取订单列表
  getOrders: (params = {}) => apiClient.get('/orders', { params }),
  
  // 获取单个订单
  getOrder: (id) => apiClient.get(`/orders/${id}`),
  
  // 更新订单状态
  updateOrder: (id, data) => apiClient.put(`/orders/${id}`, data),
};

// 通用 API 工具函数
export const commonAPI = {
  // 分页参数处理
  formatPagination: (pagination) => ({
    page: pagination.currentPage - 1,  // 后端从0开始计页
    size: pagination.pageSize,
  }),
  
  // 过滤参数处理
  formatFilters: (filters) => {
    const result = {};
    Object.keys(filters).forEach(key => {
      if (filters[key] !== null && filters[key] !== undefined && filters[key] !== '') {
        result[key] = filters[key];
      }
    });
    return result;
  }
};

export default apiClient;